package com.woniuxy.charin.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.charin.common.RedisConst;
import com.woniuxy.charin.mapper.InvestorsMapper;
import com.woniuxy.charin.mapper.InvestorsvoZbMapper;
import com.woniuxy.charin.mapper.ProjectsMapper;
import com.woniuxy.charin.model.entity.Investors;
import com.woniuxy.charin.model.entity.InvestorsvoZb;
import com.woniuxy.charin.model.entity.Projects;
import com.woniuxy.charin.model.vo.InvestorsVo;
import com.woniuxy.charin.service.InvestorsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
* @author Admin
* @description 针对表【investors】的数据库操作Service实现
* @createDate 2024-12-24 10:40:57
*/
@Service
public class InvestorsServiceImpl extends ServiceImpl<InvestorsMapper, Investors>
    implements InvestorsService{
    @Autowired
    private InvestorsMapper investorsMapper;
    @Autowired
    private ProjectsMapper projectsMapper;
    @Autowired
    private InvestorsvoZbMapper investorsvoZbMapper;
    /**
     * 查询所有投资商
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional
    @Override
    @Cacheable(cacheNames = RedisConst.INVESTORS, keyGenerator = "keyGenerator")
    public Page<InvestorsVo> getAll(Integer pageNum, Integer pageSize) {
        List<InvestorsVo>investorsVos=new ArrayList<>();
        List<Investors> list = list();
        for (int i = 0; i < list.size(); i++) {
            InvestorsVo investorsVo = new InvestorsVo();
            Investors investors = list.get(i);
            investorsVo.setId(investors.getId());
            investorsVo.setName(investors.getName());
            investorsVo.setPhoneNumber(investors.getPhoneNumber());
            investorsVo.setIsCustomer(investors.getIsCustomer());
            investorsVo.setInvestmentType(investors.getInvestmentType());
            investorsVo.setInvestmentAmount(investors.getInvestmentAmount());
            investorsVo.setStatus(investors.getStatus());
            investorsVo.setUserId(investors.getUserId());
            investorsVo.setPhotoPath(investors.getPhotoPath());
            //找子表的电站名称
            LambdaQueryWrapper<InvestorsvoZb> wrapper = Wrappers.lambdaQuery(InvestorsvoZb.class)
                    .eq(InvestorsvoZb::getInvestorsId, investors.getId());
            List<InvestorsvoZb> investorsvoZbs = investorsvoZbMapper.selectList(wrapper);
            investorsvoZbs.forEach(item->{
                investorsVo.addStationName(item.getStationName());
            });
            //找项目名称
            List<Projects> projects = projectsMapper.selectList(Wrappers.lambdaQuery(Projects.class)
                    .eq(Projects::getInvestorsId, investors.getId()));
            projects.forEach(item->{
                investorsVo.addProjects(item.getProjectName());
            });
            investorsVo.setCreateTime(investors.getCreateTime());
            investorsVos.add(investorsVo);
        }
        // 计算总记录数
        long total = investorsVos.size();

        // 创建 Page 对象，并设置分页参数
        Page<InvestorsVo> page = new Page<>(pageNum, pageSize);
        page.setTotal(total);

        // 如果当前页码超出范围，则返回空的结果集
        if (pageNum > Math.ceil((double)total / pageSize) || pageNum < 1) {
            page.setRecords(new ArrayList<>());
            return page;
        }

        // 计算分页后的起始和结束索引
        int start = (int)((pageNum - 1) * pageSize);
        int end = Math.min(start + pageSize, (int)total);

        // 使用 subList 方法获取分页后的子列表
        List<InvestorsVo> paginatedList = investorsVos.subList(start, end);

        // 设置分页后的数据到 Page 对象
        page.setRecords(paginatedList);

        return page;
    }
    @Transactional
    @Override
    @Cacheable(cacheNames = RedisConst.INVESTORS, keyGenerator = "keyGenerator")
    public Page<InvestorsVo> getInv(Integer pageNum, Integer pageSize) {
        List<InvestorsVo>investorsVos=new ArrayList<>();
        List<Investors> list = list(Wrappers.lambdaQuery(Investors.class).eq(Investors::getStatus,"待处理"));
        for (int i = 0; i < list.size(); i++) {
            InvestorsVo investorsVo = new InvestorsVo();
            Investors investors = list.get(i);
            investorsVo.setId(investors.getId());
            investorsVo.setName(investors.getName());
            investorsVo.setPhoneNumber(investors.getPhoneNumber());
            investorsVo.setIsCustomer(investors.getIsCustomer());
            investorsVo.setInvestmentType(investors.getInvestmentType());
            investorsVo.setInvestmentAmount(investors.getInvestmentAmount());
            investorsVo.setStatus(investors.getStatus());
            investorsVo.setUserId(investors.getUserId());
            investorsVo.setPhotoPath(investors.getPhotoPath());
            //找子表的电站名称
            LambdaQueryWrapper<InvestorsvoZb> wrapper = Wrappers.lambdaQuery(InvestorsvoZb.class)
                    .eq(InvestorsvoZb::getInvestorsId, investors.getId());
            List<InvestorsvoZb> investorsvoZbs = investorsvoZbMapper.selectList(wrapper);
            investorsvoZbs.forEach(item->{
                investorsVo.addStationName(item.getStationName());
            });
            //找项目名称
            List<Projects> projects = projectsMapper.selectList(Wrappers.lambdaQuery(Projects.class)
                    .eq(Projects::getInvestorsId, investors.getId()));
            projects.forEach(item->{
                investorsVo.addProjects(item.getProjectName());
            });
            investorsVo.setCreateTime(investors.getCreateTime());
            investorsVos.add(investorsVo);
        }
        // 计算总记录数
        long total = investorsVos.size();

        // 创建 Page 对象，并设置分页参数
        Page<InvestorsVo> page = new Page<>(pageNum, pageSize);
        page.setTotal(total);

        // 如果当前页码超出范围，则返回空的结果集
        if (pageNum > Math.ceil((double)total / pageSize) || pageNum < 1) {
            page.setRecords(new ArrayList<>());
            return page;
        }

        // 计算分页后的起始和结束索引
        int start = (int)((pageNum - 1) * pageSize);
        int end = Math.min(start + pageSize, (int)total);

        // 使用 subList 方法获取分页后的子列表
        List<InvestorsVo> paginatedList = investorsVos.subList(start, end);

        // 设置分页后的数据到 Page 对象
        page.setRecords(paginatedList);

        return page;
    }

    /**
     * 根据id删除单个用户
     * @param invId
     */
    @Transactional
    @Override
    public void deleteById(Integer invId) {
        removeById(invId);
        investorsvoZbMapper.delete(Wrappers.lambdaQuery(InvestorsvoZb.class)
                                            .eq(InvestorsvoZb::getInvestorsId,invId));
        projectsMapper.delete(Wrappers.lambdaQuery(Projects.class)
                                        .eq(Projects::getInvestorsId,invId));
    }
    @Transactional
    @Override
    public void batchDelete(Integer[] invIds) {
        List<Integer> list = Arrays.asList(invIds);
        removeByIds(list);
        QueryWrapper<Projects> wrapper = new QueryWrapper<Projects>().in("investors_id",list);
        projectsMapper.delete(wrapper);
        QueryWrapper<InvestorsvoZb> wrapper1 = new QueryWrapper<InvestorsvoZb>().in("investors_id", list);
        investorsvoZbMapper.delete(wrapper1);
    }

    @Override
    public Investors findById(Integer invId) {
        Investors investors = getById(invId);
        LambdaQueryWrapper<InvestorsvoZb> wrapper = Wrappers.lambdaQuery(InvestorsvoZb.class)
                .eq(InvestorsvoZb::getInvestorsId, investors.getId());
        List<InvestorsvoZb> investorsvoZbs = investorsvoZbMapper.selectList(wrapper);
        investorsvoZbs.forEach(item->{
            investors.getInvestorsvoZbs().add(item);
        });
        //找项目名称
        List<Projects> projects = projectsMapper.selectList(Wrappers.lambdaQuery(Projects.class)
                .eq(Projects::getInvestorsId, investors.getId()));
        projects.forEach(item->{
            investors.getProjects().add(item);
        });
        return investors;
    }

    /**
     * 根据条件查询
     * @param params
     * @return
     */
    @Override
    public Page<InvestorsVo> query(Map<String, String> params) {
        int pageNum = Integer.valueOf(params.get("pageNum"));
        int pageSize = Integer.parseInt(params.get("pageSize"));
        String name=params.get("name");
        String phoneNumber=params.get("phoneNumber");
        LambdaQueryWrapper<Investors> wrapper = Wrappers.lambdaQuery(Investors.class);
        if (name!=null){
            wrapper.eq(Investors::getName,name);
        }
        if (phoneNumber!=null){
            wrapper.eq(Investors::getPhoneNumber,phoneNumber);
        }
        List<InvestorsVo>investorsVos=new ArrayList<>();
        List<Investors> list = list(wrapper);
        if (list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                InvestorsVo investorsVo = new InvestorsVo();
                Investors investors = list.get(i);
                investorsVo.setId(investors.getId());
                investorsVo.setName(investors.getName());
                investorsVo.setPhoneNumber(investors.getPhoneNumber());
                investorsVo.setIsCustomer(investors.getIsCustomer());
                investorsVo.setInvestmentType(investors.getInvestmentType());
                investorsVo.setInvestmentAmount(investors.getInvestmentAmount());
                //找子表的电站名称
                LambdaQueryWrapper<InvestorsvoZb> wrapper2 = Wrappers.lambdaQuery(InvestorsvoZb.class)
                        .eq(InvestorsvoZb::getInvestorsId, investors.getId());
                List<InvestorsvoZb> investorsvoZbs = investorsvoZbMapper.selectList(wrapper2);
                investorsvoZbs.forEach(item->{
                    investorsVo.addStationName(item.getStationName());
                });
                //找项目名称
                List<Projects> projects = projectsMapper.selectList(Wrappers.lambdaQuery(Projects.class)
                        .eq(Projects::getInvestorsId, investors.getId()));
                projects.forEach(item->{
                    investorsVo.addProjects(item.getProjectName());
                });
                investorsVo.setCreateTime(investors.getCreateTime());
                investorsVos.add(investorsVo);
            }
            // 计算总记录数
            long total = investorsVos.size();

            // 创建 Page 对象，并设置分页参数
            Page<InvestorsVo> page = new Page<>(pageNum, pageSize);
            page.setTotal(total);

            // 如果当前页码超出范围，则返回空的结果集
            if (pageNum > Math.ceil((double)total / pageSize) || pageNum < 1) {
                page.setRecords(new ArrayList<>());
                return page;
            }

            // 计算分页后的起始和结束索引
            int start = (int)((pageNum - 1) * pageSize);
            int end = Math.min(start + pageSize, (int)total);

            // 使用 subList 方法获取分页后的子列表
            List<InvestorsVo> paginatedList = investorsVos.subList(start, end);

            // 设置分页后的数据到 Page 对象
            page.setRecords(paginatedList);

            return page;
        }
        // 计算总记录数
        long total = 0;

        // 创建 Page 对象，并设置分页参数
        Page<InvestorsVo> page = new Page<>(pageNum, pageSize);
        page.setTotal(total);

        // 如果当前页码超出范围，则返回空的结果集
        if (pageNum > Math.ceil((double)total / pageSize) || pageNum < 1) {
            page.setRecords(new ArrayList<>());
            return page;
        }

        // 计算分页后的起始和结束索引
        int start = (int)((pageNum - 1) * pageSize);
        int end = Math.min(start + pageSize, (int)total);

        // 使用 subList 方法获取分页后的子列表
        List<InvestorsVo> paginatedList = investorsVos.subList(start, end);

        // 设置分页后的数据到 Page 对象
        page.setRecords(paginatedList);

        return page;
    }

    @Override
    public List<InvestorsVo> getByU(Integer userId) {
        List<InvestorsVo>investorsVos=new ArrayList<>();
        List<Investors> list = list(Wrappers.lambdaQuery(Investors.class).eq(Investors::getUserId,userId).eq(Investors::getStatus,"已通过"));
        for (int i = 0; i < list.size(); i++) {
            InvestorsVo investorsVo = new InvestorsVo();
            Investors investors = list.get(i);
            investorsVo.setId(investors.getId());
            investorsVo.setName(investors.getName());
            investorsVo.setPhoneNumber(investors.getPhoneNumber());
            investorsVo.setIsCustomer(investors.getIsCustomer());
            investorsVo.setInvestmentType(investors.getInvestmentType());
            investorsVo.setInvestmentAmount(investors.getInvestmentAmount());
            investorsVo.setStatus(investors.getStatus());
            investorsVo.setUserId(investors.getUserId());
            investorsVo.setPhotoPath(investors.getPhotoPath());
            //找子表的电站名称
            LambdaQueryWrapper<InvestorsvoZb> wrapper = Wrappers.lambdaQuery(InvestorsvoZb.class)
                    .eq(InvestorsvoZb::getInvestorsId, investors.getId());
            List<InvestorsvoZb> investorsvoZbs = investorsvoZbMapper.selectList(wrapper);
            investorsvoZbs.forEach(item->{
                investorsVo.addzbs(item);
            });
            //找项目名称
            List<Projects> projects = projectsMapper.selectList(Wrappers.lambdaQuery(Projects.class)
                    .eq(Projects::getInvestorsId, investors.getId()));
            projects.forEach(item->{
                investorsVo.addProjects(item.getProjectName());
            });
            investorsVo.setCreateTime(investors.getCreateTime());
            investorsVos.add(investorsVo);
        }
        return investorsVos;
    }
}




